package com.lion.queue.runner;

import java.util.concurrent.PriorityBlockingQueue;
/**
 * 队列
 * @author liyongyao
 *
 * @param <T>
 */
public class Queue<T> {
	private Integer maxSize = 10;
	private PriorityBlockingQueue<QueueItem<T>> blockingQueue;

	/**
	 * 获得一个不限制大小的队列
	 */
	public Queue() {
		this(0);
	}

	/**
	 * 获得一个固定大小的队列
	 * @param maxSize
	 *            队列最大值，小于或等于0时不限制大小，默认大小为10
	 */
	public Queue(Integer maxSize) {
		if (maxSize != null && maxSize > 0) {
			this.maxSize = maxSize;
		}
		blockingQueue = new PriorityBlockingQueue<QueueItem<T>>();
	}

	public PriorityBlockingQueue<QueueItem<T>> getBlockingQueue() {
		return blockingQueue;
	}

	/**
	 * 添加到队列
	 * 
	 * @param item
	 * @return
	 */
	public boolean add(QueueItem<T> item) {
		if (isFull()) {
			return false;
		}
		return getBlockingQueue().offer(item);
	}

	/**
	 * 添加到队列
	 * 
	 * @param entity
	 * @param priority
	 *            优先级，数字，越大级别越高
	 * @return
	 */
	public boolean add(T entity, int priority) {
		QueueItem<T> item = new QueueItem<T>();
		item.setEntity(entity);
		item.setPriority(priority);
		return add(item);
	}

	/**
	 * 取队列,null时说明队列为空
	 * 
	 * @return
	 */
	public QueueItem<T> poll() {
		return getBlockingQueue().poll();
	}

	public boolean contains(QueueItem<T> item) {
		return getBlockingQueue().contains(item);
	}

	public boolean contains(T entity) {
		QueueItem<T> item = new QueueItem<T>();
		item.setEntity(entity);
		return getBlockingQueue().contains(item);
	}

	public boolean isFull() {
		if (maxSize > 0) {
			return getBlockingQueue().size() >= maxSize;
		} else {
			return false;
		}
	}

}
